# coding: utf-8
import subprocess
import sys

from PySide6.QtCore import Qt
from PySide6.QtGui import QColor
from PySide6.QtWidgets import QVBoxLayout, QHBoxLayout, QFileDialog
from qfluentwidgets import IconWidget, TitleLabel, CaptionLabel, PushButton, MessageBox, GroupHeaderCardWidget

from common import SingleIcon
from components import VerticalScrollArea, ProcessDialog


class DeploymentInterface(VerticalScrollArea):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.filename = ''
        self.iconWidget = IconWidget(SingleIcon.Pyinstaller, self)
        self.titleLabel = TitleLabel('PyInstaller', self)
        self.descriptionLabel = CaptionLabel(
            "PyInstaller是一个开源的Python编译器，它可以将Python代码编译成可执行文件，并将其打包成可移植的格式，以便于分发和部署。",
            self
        )
        self.groupBox = GroupHeaderCardWidget('PyInstaller设置', self)
        self.selectInterpreterBtn = PushButton('选择解释器', self)
        self.interpreterCard = self.groupBox.addGroup(SingleIcon.Python, '解释器设置', '请选择Python解释器路径',
                                                      self.selectInterpreterBtn)

        self.pythonVersionLabel = CaptionLabel('未检测到Python版本', self)

        self.pyinstallerVersionLabel = CaptionLabel('未检测到PyInstaller版本', self)

        self.__initWidgets()

    def __initWidgets(self):
        self.setObjectName('DeploymentInterface')

        self.iconWidget.setFixedSize(100, 100)

        self.descriptionLabel.setWordWrap(True)
        self.descriptionLabel.setTextColor(QColor(96, 96, 96), QColor(206, 206, 206))
        self.stateToolTip.setContent('正在获取Python解释器信息，请稍后...')

        pythonVersionCard = self.groupBox.addGroup(SingleIcon.Rocket, 'Python版本', '', self.pythonVersionLabel)
        pythonVersionCard.contentLabel.hide()
        pyinstallerVersionCard = self.groupBox.addGroup(SingleIcon.Joystick, 'PyInstaller版本', '',
                                                        self.pyinstallerVersionLabel)
        pyinstallerVersionCard.contentLabel.hide()

        self.__initLayout()
        self.__connectSignals()

    def __initLayout(self):
        horizontalLayout = QHBoxLayout()
        verticalLayout = QVBoxLayout()
        verticalLayout.setAlignment(Qt.AlignmentFlag.AlignVCenter)
        verticalLayout.addWidget(self.titleLabel)
        verticalLayout.addWidget(self.descriptionLabel)
        horizontalLayout.addWidget(self.iconWidget)
        horizontalLayout.addLayout(verticalLayout)

        self.setLayoutContentsMargins(0, 0, 10, 0)
        self.addLayout(horizontalLayout, 0)
        self.addSpacing(30)
        self.addWidget(self.groupBox)

    def __connectSignals(self):
        self.selectInterpreterBtn.clicked.connect(self.__selectInterpreter)

    def __selectInterpreter(self):
        if sys.platform == 'win32':
            filter_ = 'Python解释器(*.exe)'
        else:
            filter_ = 'Python解释器(*)'
        fileName, _ = QFileDialog.getOpenFileName(self, '选择Python解释器', '', filter_, '')
        if not fileName:
            return
        self.filename = fileName
        self.interpreterCard.setContent(fileName)
        self.load(
            lambda: subprocess.check_output(
                [fileName, '-c',
                 '''
try:
    import PyInstaller
    print(PyInstaller.__version__)
except ImportError:
    pass
                '''], text=True),
            slot=self.__showPyinstallerVersion
        )
        self.load(
            lambda: subprocess.check_output([fileName, '-c', 'import platform; print(platform.python_version())'],
                                            text=True),
            slot=self.__showPythonVersion
        )

    def __showPyinstallerVersion(self, output: str):
        if output:
            self.pyinstallerVersionLabel.setText(output.strip())
        else:
            self.pyinstallerVersionLabel.setText('PyInstaller版本: 未安装')
            dialog = MessageBox('提示', '未检测到PyInstaller，是否安装PyInstaller？', self.window())
            if dialog.exec():
                process = ProcessDialog(self.window())
                process.run(self.filename,
                            ['-m', 'pip', 'install', 'PyInstaller', '-i', 'https://pypi.tuna.tsinghua.edu.cn/simple'])
                process.exec()

    def __showPythonVersion(self, output: str):
        if output:
            self.pythonVersionLabel.setText(output.strip())
